## Copyright 2002-2003 Andrew Loewenstern, All Rights Reserved
## Copyright 2007 Roee Shlomo, All Rights Reserved
# see LICENSE.txt for license information

from hashlib import sha1
import random

#this is ugly, hopefully os.entropy will be in 2.4
try:
    from entropy import entropy
except ImportError:
    def entropy(n):
        s = ''
        for i in range(n):
            s += chr(random.randint(0,255))
        return s

def intify(hstr):
    """20 bit hash, big-endian -> long python integer"""
    assert len(hstr) == 20
    return long(hstr.encode('hex'), 16)

def stringify(num):
    """long int -> 20-character string"""
    str = hex(num)[2:]
    if str[-1] == 'L':
        str = str[:-1]
    if len(str) % 2 != 0:
        str = '0' + str
    str = str.decode('hex')
    return (20 - len(str)) *'\x00' + str
    
def distance(a, b):
    """distance between two 160-bit hashes expressed as 20-character strings"""
    return intify(a) ^ intify(b)


def newID(digest = True):
    """returns a new pseudorandom globally unique ID string"""
    h = sha1()
    h.update(entropy(20))
    if digest:
        h = h.digest()
    return h

def newIDInRange(min, max):
    return stringify(randRange(min,max))
    
def randRange(min, max):
    return min + intify(newID()) % (max - min)
    
def newTID():
    return randRange(-2**30, 2**30)
